package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO 菜品分页查询条件
     * @return 分页查询结果
     */
    @Override
    public PageResult getDishPage(DishPageQueryDTO dishPageQueryDTO) {
        // 开始分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        // 分页查询
        Page<DishVO> page = dishMapper.selectPage(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增菜品
     *
     * @param dishDTO 菜品信息
     */
    @Override
    public void addDish(DishDTO dishDTO) {
        // 拷贝属性到实体
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 设置状态默认为停售 0
        dish.setStatus(StatusConstant.DISABLE);
        // 添加菜品操作
        dishMapper.insert(dish);
        // 获取添加菜品主键
        Long dishId = dish.getId();

        // 添加口味操作
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors == null || flavors.isEmpty()) return;
        flavors.forEach(item -> item.setDishId(dishId));
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 根据 ID 查询菜品
     *
     * @param id 菜品id
     * @return 菜品信息以及关联的口味信息
     */
    @Override
    public DishVO getDishById(Long id) {
        // 根据id查询菜品基本信息
        Dish dish = dishMapper.getById(id);
        // 根据菜品id查询关联口味信息
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);
        // 封装菜品基本信息与口味信息
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 更新菜品
     *
     * @param dishDTO 菜品信息
     */
    @Override
    public void updateDish(DishDTO dishDTO) {
        // 更新菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        // 清空菜品列表缓存
        Set redisKeys = redisTemplate.keys("dishList::*");
        redisTemplate.delete(redisKeys);

        // 更新菜品关联的口味
        Long dishId = dishDTO.getId();
        // 1.先根据菜品ID删除原有的所有口味
        dishFlavorMapper.deleteByDishId(dishId);
        // 2.再插入新增的所有口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors.isEmpty()) return;
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 更新菜品状态
     *
     * @param status 状态
     * @param id     菜品id
     */
    @Override
    public void updateDishStatus(Integer status, Long id) {
        // 复用更新菜品操作
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);

        // 清空菜品列表缓存
        Set redisKeys = redisTemplate.keys("dishList::*");
        redisTemplate.delete(redisKeys);
    }

    /**
     * 删除菜品
     *
     * @param ids 菜品id集合
     */
    @Override
    public void deleteDish(List<Long> ids) {
        ids.forEach(id -> {
            // 如果是起售状态，不可删除
            Dish dish = dishMapper.getById(id);
            // if(dish.getStatus() == StatusConstant.ENABLE) {
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            // 如果有关联套餐，不可删除
            Integer setmealCount = setmealDishMapper.countByDishId(id);
            if (setmealCount > 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        });
        // 删除菜品
        dishMapper.deleteBatch(ids);
        // 删除菜品关联的口味
        ids.forEach(dishId -> dishFlavorMapper.deleteByDishId(dishId));
        // 清空菜品列表缓存
        Set redisKeys = redisTemplate.keys("dishList::*");
        redisTemplate.delete(redisKeys);
    }

    /**
     * 查询带有口味的菜品列表
     * @param dish 菜品实体
     * @return 菜品列表
     */
    @Override
    public List<DishVO> getDishListWithFlavor(Dish dish) {
        // 使用 Redis 缓存数据
        // 组装 Redis 存储 key dish::categoryId
        String redisKey = "dishList::" + dish.getCategoryId();
        // 1.查询Redis是否有缓存，有则直接返回
        List<DishVO> cacheDishList = (List<DishVO>) redisTemplate.opsForValue().get(redisKey);
        if(cacheDishList != null && !cacheDishList.isEmpty()) {
            return cacheDishList;
        }
        // 2.无则查询数据库，添加到Redis缓存
        List<Dish> dishList = dishMapper.selectList(dish);
        List<DishVO> dishVOList = new ArrayList<>();
        if(dishList.isEmpty()) return dishVOList;
        dishList.forEach(d -> {
            // 拷贝基本属性
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);
            // 根据菜品id查询关联口味，并赋值
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);
            // 添加到返回列表中
            dishVOList.add(dishVO);
        });
        // 添加到Redis缓存
        redisTemplate.opsForValue().set(redisKey, dishVOList);
        return dishVOList;
    }
}
